package com.atguigu.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.enume.OrderStatusEnum;
import com.atguigu.common.to.OrderTO;
import com.atguigu.common.to.SkuHasStockVo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimall.ware.feign.OrderFeignService;
import com.atguigu.gulimall.ware.feign.ProductFeignService;
import com.atguigu.gulimall.ware.service.WareOrderTaskDetailService;
import com.atguigu.gulimall.ware.service.WareOrderTaskService;
import com.atguigu.gulimall.ware.to.StockDetailTO;
import com.atguigu.gulimall.ware.to.StockLockedTO;
import com.atguigu.gulimall.ware.vo.*;
import com.rabbitmq.client.Channel;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Resource
    WareSkuDao wareSkuDao;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    WareOrderTaskService wareOrderTaskService;
    @Autowired
    WareOrderTaskDetailService wareOrderTaskDetailService;
    @Autowired
    OrderFeignService orderFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        /**
         * skuId: 1
         * wareId: 2
         */
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if(!StringUtils.isEmpty(skuId)){
            queryWrapper.eq("sku_id",skuId);
        }

        String wareId = (String) params.get("wareId");
        if(!StringUtils.isEmpty(wareId)){
            queryWrapper.eq("ware_id",wareId);
        }


        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //1、判断如果还没有这个库存记录新增
        List<WareSkuEntity> entities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if(entities == null || entities.size() == 0){
            WareSkuEntity skuEntity = new WareSkuEntity();
            skuEntity.setSkuId(skuId);
            skuEntity.setStock(skuNum);
            skuEntity.setWareId(wareId);
            skuEntity.setStockLocked(0);
            //TODO 远程查询sku的名字，如果失败，整个事务无需回滚
            //1、自己catch异常
            //TODO 还可以用什么办法让异常出现以后不回滚？高级
            try {
                R info = productFeignService.info(skuId);
                Map<String,Object> data = (Map<String, Object>) info.get("skuInfo");

                if(info.getCode() == 0){
                    skuEntity.setSkuName((String) data.get("skuName"));
                }
            }catch (Exception e){

            }

            wareSkuDao.insert(skuEntity);
        }else{
            wareSkuDao.addStock(skuId,wareId,skuNum);
        }

    }

    @Override
    public List<SkuHasStockVo> getHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
            SkuHasStockVo vo = new SkuHasStockVo();
            //查询当前SKU的总库存量（总库存 减去 已锁定库存）
            Long count = baseMapper.getSkuStock(skuId);
            vo.setSkuId(skuId);
            vo.setHasStock(count == null ? false : count > 0);
            return vo;
        }).collect(Collectors.toList());
        return collect;

    }


    @Override
    @Transactional
    public Boolean orderLockStock(WareSkuLockVO vo) {

        //保存库存工作单的详情，方便追溯
        WareOrderTaskEntity wareOrderTaskEntity = new WareOrderTaskEntity();
        wareOrderTaskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskService.save(wareOrderTaskEntity);

        //严格流程：按照下单的收获地址，找到一个就近仓库，锁定库存
        //这里简化流程：找到商品在哪个仓库都有库存
        List<OrderItemVO> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            stock.setNum(item.getCount());
            //查询这个商品在哪个仓库有库存
            List<Long> wareIds = wareSkuDao.listWareIdHasSkuStock(skuId);
            stock.setWareId(wareIds);
            return stock;
        }).collect(Collectors.toList());
        //锁定库存
        for (SkuWareHasStock hasStock : collect) {
            //标记锁库存是否成功
            Boolean skuStocked = false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();
            if (wareIds == null || wareIds.isEmpty()) {
                //没有任何仓库有这个商品的库存
                throw new RuntimeException("商品ID["+skuId + "]库存为零");
            }
            for (Long wareId : wareIds) {
                Long count = wareSkuDao.lockSkuStock(skuId, wareId, hasStock.getNum());
                //只要有一个仓库的库存锁定成功即可
                if (count != 0) {
                    skuStocked = true;

                    //创建库存工作单详情
                    WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity(null,skuId,"query name from skuId = "+skuId,hasStock.getNum(),wareOrderTaskEntity.getId(),wareId,1);
                    wareOrderTaskDetailService.save(wareOrderTaskDetailEntity);
                    //封装数据传输对象
                    StockLockedTO stockLockedTO = new StockLockedTO();
                    stockLockedTO.setId(wareOrderTaskEntity.getId());
                    StockDetailTO stockDetail = new StockDetailTO();
                    BeanUtils.copyProperties(wareOrderTaskDetailEntity,stockDetail);
                    stockLockedTO.setDetail(stockDetail);
                    //将库存锁定成功的消息发到MQ
                    rabbitTemplate.convertAndSend("stock-event-exchange","stock.delay",stockLockedTO);
                    break;
                }
            }
            if (!skuStocked) {
                throw new RuntimeException("商品ID["+skuId + "]库存为零");
            }
        }
        //如果没抛异常表示全部锁定成功
        return true;
    }


    @Override
    @Transactional
    public void test() {
        WareSkuEntity wareSkuEntity = new WareSkuEntity();
        wareSkuEntity.setSkuId(1L);
        this.save(wareSkuEntity);
    }

    /**
     * 库存自动解锁 （服务器的后台操作，无需登录，设置相关远程服务的拦截器在登录验证时放行）
     * 下单成功，库存锁定成功，接下来的业务调用失败导致订单回滚或订单失效，之前锁定的库存就要自动解锁
     */
    @Override
    public void unlockStock(StockLockedTO to) throws Exception{

        //解锁
        //1、查询数据库关于这个订单的库存锁定信息
        //没有：无需解锁，库存锁定失败，库存回滚。
        //有：进行解锁
        Long id = to.getId();//库存工作单的ID
        StockDetailTO detail = to.getDetail();
        WareOrderTaskDetailEntity detailEntity = wareOrderTaskDetailService.getById(detail.getId());
        if (detailEntity != null) {
            WareOrderTaskEntity orderTaskEntity = wareOrderTaskService.getById(id);
            R r = orderFeignService.getOrderStatus(orderTaskEntity.getOrderSn());
            if (r.getCode() == 0) {
                //查询订单信息
                OrderVO data = r.getData(new TypeReference<OrderVO>() {});
                //订单不存在、已取消、工作单锁定状态，才能解锁库存
                if ((data == null || data.getStatus() == OrderStatusEnum.CANCLED.getCode()) && detailEntity.getLockStatus() == 1) {
                    //进行解锁
                    wareSkuDao.unLockStock(detail.getSkuId(),detail.getWareId(),detail.getSkuNum());
                    //更新库存工作单的状态
                    detailEntity.setLockStatus(2);//2 已解锁
                    wareOrderTaskDetailService.updateById(detailEntity);
                }
            }
        }
    }

    //防止订单服务卡顿，导致订单状态消息一直改不了，库存消息优先到期，检查订单为新建状态，什么都不做就走了，最后卡顿的订单永远不能解锁库存
    @Override
    public void unlockStock(OrderTO orderTO) {
        String orderSn = orderTO.getOrderSn();
        //检查最新库存状态，防止重复解锁
        WareOrderTaskEntity task = wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
        //按照工作单找到所有没解锁的库存进行解锁
        List<WareOrderTaskDetailEntity> list = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id", task.getId()).eq("lock_status", 1));
        for (WareOrderTaskDetailEntity detail : list) {
            //进行解锁
            wareSkuDao.unLockStock(detail.getSkuId(),detail.getWareId(),detail.getSkuNum());
        }

    }

}